<template>
  <div class="app-container">
    <!-- 查询条件开始  -->
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="字典名称" prop="dictName">
        <el-input
          v-model="queryParams.dictName"
          placeholder="请输入字典名称"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="字典类型" prop="dictType">
        <el-input
          v-model="queryParams.dictType"
          placeholder="请输入字典类型"
          clearable
          size="small"
          style="width:240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          size="small"
          style="width:240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width:240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholde="开始日期"
          end-placeholde="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 查询条件结束  -->

    <!-- 表格工具按钮开始 -->
    <el-row :gutter="10" style="margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        <el-button type="wanging" icon="el-icon-refresh" size="mini" @click="handelRefresh" />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-refresh" size="mini" @click="handleCacheAsync">缓存同步</el-button>
        <el-button type="error" icon="el-icon-error" size="mini" @click="clearCacheAsync">清空缓存</el-button>
      </el-col>
    </el-row>
    <!-- 表格工具按钮结束 -->

    <!-- 数据表格开始 -->
    <el-table v-loading="loading" border :data="dictTypeTableList" @selection-change="handleSelectionChnage">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字典编号" prop="dictId" align="center" />
      <el-table-column label="字典名称" prop="dictName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="字典类型" prop="dictType" align="center" :show-overflow-tooltip="true">
        <!-- // 跳转路由查看该字典类型下的 字典数据 -->
        <template slot-scope="scope">
          <el-tag
            :type="'primary'"
            disable-transitions
          >
            <router-link :to="'/dict/data/' + scope.row.dictId" class="link-type">
              <span>{{ scope.row.dictType }}</span>
            </router-link>
          </el-tag>
        </template>
      </el-table-column>
      <!--prop="status" :formatter="statusFormatter"-->
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="top">
            <p>{{ scope.row.remark }}</p>
            <div slot="reference" class="name-wrapper">
              <el-tag size="medium" :type="scope.row.status === '0' ? 'primary' : 'danger'">
                {{ scope.row | statusFormatters(scope.row.status,statusOptions) }}
              </el-tag>
            </div>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="180">
        <template slot-scope="scope">
          <el-tag
            :type="'success'"
            disable-transitions
          > {{ scope.row.createTime }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="el-icon-delete" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 数据表格结束 -->

    <!-- 分页控件开始 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getDictTypeList" />
    <!-- 分页控件结束 -->

    <!-- 添加修改弹出层开始 -->
    <el-dialog
      v-loading="dialogloading"
      :title="title"
      :visible.sync="open"
      width="500px"
      center
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" clearable size="small" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
              :value="dict.dictValue"
            >{{ dict.dictLabel }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入字典备注" clearable size="small" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit('form')">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改弹出层结束 -->
  </div>
</template>

<script>
// 引入 api接口 调用后端数据
// import http from '@/utils/request'
import { listForPage, addDictType, updateDictType, deleteDictTypeByIds, dictCacheAsync, dictClearCacheAsync, getDictTypeById } from '@/api/system/dict/type'
import Pagination from '@/components/Pagination'
export default {
  inject: ['reload'],
  components: {
    Pagination
  },
  filters: {
    // 自定义美化翻译状态 0
    statusFormatters: function(datas, rows, statusOptions) {
      var actions = []
      Object.keys(statusOptions).map((key) => {
        if (statusOptions[key].dictValue === rows) {
          actions.push(statusOptions[key].dictLabel)
          return false
        }
      })
      return actions.join('')
    }
  },
  // 定义页面数据
  data() {
    return {
      dialogVisible: false,
      // 是否启用遮罩层
      loading: false,
      // 弹出层遮罩层
      dialogloading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 分页数据总条数
      total: 0,
      // 字典表格数据
      dictTypeTableList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单数据
      form: {
        status: true
      },
      // 表单校验
      rules: {
        dictName: [
          { required: true, message: '字典名称不能为空', trigger: 'blur' }
        ],
        dictType: [
          { required: true, message: '字典类型不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  // 生命周期--钩子函数--页面初始化完毕调用
  created() {
    // 查询表格数据
    this.getDictTypeList()
    // 注入字典数据
    this.getDataByTypeCacheAsync()
  },
  // 专门用于方法定义
  methods: {
    // 使用全局的根据字典类型查询字典数据的方法查询字典数据
    getDataByTypeCacheAsync() {
      // 查询状态字典信息
      this.getDataByType('sys_normal_disable').then(res => {
        if (res.data === null) {
          this.msgError('字典缓存消失请重新录入!!')
          this.statusOptions = res.data
        } else {
          this.statusOptions = res.data
        }
      }).catch(error => {
        this.msgError(error.msg)
      })
    },
    // 查询表格数据
    getDictTypeList() {
      this.loading = true // 打开遮罩
      listForPage(this.addDateRange(this.queryParams, this.dateRange)).then(res => {
        this.dictTypeTableList = res.data
        this.total = res.total
        this.loading = false// 关闭遮罩
      })
    },
    // 翻译状态
    statusFormatter(row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 条件查询
    handleQuery() {
      this.getDictTypeList()
    },
    // 重置查询条件
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.getDictTypeList()
    },
    // 数据表格的多选择框选择时触发
    handleSelectionChnage(selection) {
      // 记录选中的ID/删除
      this.ids = selection.map(item => item.dictId)
      // 修改 如果选中数大于1
      this.single = selection.length !== 1
      // 删除 如果选中的数不为空 false/true
      this.multiple = !selection.length
    },
    // 分页pageSize变化时触发
    handleSizeChange(page, limit) {
      this.queryParams.pageSize = limit
      // 重新查询
      this.getDictTypeList()
    },
    // 点击切换页数触发
    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      // 重新查询
      this.getDictTypeList()
    },
    // 打开添加的弹出层
    handleAdd() {
      this.open = true
      this.title = '添加字典类型'
      this.reset()
    },
    // 打开修改的弹出层
    handleUpdate(row) {
      this.dialogloading = true
      // 判断如果row为空那么就使用选中的
      const dataDictId = row.dictId || this.ids[0]
      console.log(dataDictId)
      this.open = true
      this.title = '修改字典类型'
      this.reset()
      // // 根据row.dictid过滤一个字典信息
      // const dataDictType = this.dictTypeTableList.filter(e => e.dictId === dataDictId)
      // if (dataDictType != null && undefined !== dataDictType) this.form = dataDictType[0]
      // console.log(dataDictType)
      // 根据dictId查询一个字典信息
      getDictTypeById(dataDictId).then(res => {
        this.form = res.data
        this.dialogloading = false
      })
    },
    // 删除
    handleDelete(row) {
      const dictIds = row.dictId || this.ids
      this.$confirm('此操作将永久删除该字典数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteDictTypeByIds(dictIds).then(res => {
          this.loading = false
          this.msgSuccess('删除成功')
          this.reset()
          this.getDictTypeList()// 全查询
        })
      }).catch(() => {
        this.msgError('删除已取消')
        this.loading = false
      })
    },
    // 同步数据到缓存管理器
    handleCacheAsync() {
      this.loading = true
      dictCacheAsync().then(res => {
        this.notSuccess(res.msg)
        this.getDictTypeList()
        this.getDataByTypeCacheAsync()
        this.loading = false
      })
    },
    // 清空缓存
    clearCacheAsync() {
      this.loading = true
      // 测试代码生成器请求
      // http({
      //   url: http.adornUrl('/system/dict/type/dictClearCacheAsync'),
      //   method: 'post'
      // }).then(res => {
      //   this.notSuccess(res.msg)
      //   this.getDictTypeList()
      //   this.loading = false
      // }).catch(error => {
      //   console.log(error)
      // })
      dictClearCacheAsync().then(res => {
        this.notSuccess(res.msg)
        this.getDictTypeList()
        this.getDataByTypeCacheAsync()
        this.loading = false
      })
    },
    // 弹出层的提交 添加or更新
    handleSubmit(fromName) {
      this.loading = true
      this.$refs[fromName].validate((valid) => {
        if (valid) {
          if (this.form.dictId === undefined) {
            addDictType(this.form).then(res => {
              // 提示
              if (res.code === 200) this.msgSuccess(res.msg)
              else this.msgError(res.msg)
              // 刷新一下下
              this.getDictTypeList()
              // 关闭加载遮罩
              this.loading = false
              // 关闭遮罩
              this.open = false
            }).catch(() => {
              this.loading = false
            })
          } else {
            // 修改
            updateDictType(this.form).then(res => {
              // 提示
              if (res.code === 200) this.msgSuccess(res.msg)
              else this.msgError(res.msg)
              // 刷新一下下
              this.getDictTypeList()
              // 关闭加载遮罩
              this.loading = false
              // 关闭遮罩
              this.open = false
            }).catch(() => {
              this.loading = false
            })
          }
        } else {
          this.loading = false
          return false
        }
      })
    },
    handelRefresh() {
      this.reload()
    },
    // 弹出层的取消
    cancel() {
      this.open = false
    },
    // 重置表单
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: '0',
        remark: undefined
      }
      // 调用全局重置表单方法
      this.resetForm('form')
    }
  }
}
</script>
